﻿using System;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
using System.IO;
using System.Text;
namespace Codematic
{
    /// <summary>
    /// DbToWord 的摘要说明。
    /// </summary>
    public  partial class DbToScript : System.Windows.Forms.Form
    {
        #region
     
    
        #endregion

        LTP.IDBO.IDbScriptBuilder dsb;
        LTP.IDBO.IDbObject dbobj;
        string DbName = "master";
        private PictureBox pictureBox1;
        Thread mythread;
        delegate void SetBtnEnableCallback();
        delegate void SetBtnDisableCallback();
        delegate void SetlblStatuCallback(string text);
        delegate void SetProBar1MaxCallback(int val);
        delegate void SetProBar1ValCallback(int val);

        public DbToScript(string longservername)
        {
            InitializeComponent();
            dsb = ObjHelper.CreatDsb(longservername);
            dbobj = ObjHelper.CreatDbObj(longservername);

            int s = longservername.IndexOf("(");
            string server = longservername.Substring(0, s);
            this.lblServer.Text = server;

            List<string> dblist = dbobj.GetDBList();
            if (dblist != null)
            {
                if (dblist.Count > 0)
                {
                    foreach (string dbname in dblist)
                    {
                        this.cmbDB.Items.Add(dbname);
                    }
                }
            }

            //DataTable dt = dbobj.GetDBList();
            //if (dt != null)
            //{
            //    foreach (DataRow row in dt.Rows)
            //    {
            //        string dbname = row["name"].ToString();
            //        this.cmbDB.Items.Add(dbname);
            //    }
            //}
            this.btn_Creat.Enabled = false;
            if (cmbDB.Items.Count > 0)
            {
                this.cmbDB.SelectedIndex = 0;
            }

        }

        public DbToScript(string longservername, string dbname)
        {
            InitializeComponent();
            DbName = dbname;
            dsb = ObjHelper.CreatDsb(longservername);
            dbobj = ObjHelper.CreatDbObj(longservername);
            this.lblServer.Text = longservername;

            List<string> dblist = dbobj.GetDBList();
            if (dblist != null)
            {
                if (dblist.Count > 0)
                {
                    foreach (string name in dblist)
                    {
                        this.cmbDB.Items.Add(name);
                    }
                }
            }
            //DataTable dt = dbobj.GetDBList();
            //if (dt != null)
            //{
            //    foreach (DataRow row in dt.Rows)
            //    {                    
            //        this.cmbDB.Items.Add(row["name"].ToString());
            //    }
            //}
            this.btn_Creat.Enabled = false;
            this.cmbDB.Text = DbName;

        }

    

        private void DbToWord_Load(object sender, System.EventArgs e)
        {

        }

        private void cmbDB_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            DbName = cmbDB.Text;
            List<string> tabNames = dbobj.GetTables(DbName);

            this.listTable1.Items.Clear();
            this.listTable2.Items.Clear();

            if (tabNames.Count > 0)
            {
                foreach (string tabname in tabNames)
                {
                    listTable1.Items.Add(tabname);
                }
            }
            IsHasItem();
        }

        #region 按钮操作

        private void btn_Addlist_Click(object sender, System.EventArgs e)
        {
            int c = this.listTable1.Items.Count;
            for (int i = 0; i < c; i++)
            {
                this.listTable2.Items.Add(this.listTable1.Items[i]);
            }
            this.listTable1.Items.Clear();

            IsHasItem();
        }

        private void btn_Add_Click(object sender, System.EventArgs e)
        {

            int c = this.listTable1.SelectedItems.Count;
            ListBox.SelectedObjectCollection objs = this.listTable1.SelectedItems;
            for (int i = 0; i < c; i++)
            {
                this.listTable2.Items.Add(listTable1.SelectedItems[i]);

            }
            for (int i = 0; i < c; i++)
            {
                if (this.listTable1.SelectedItems.Count > 0)
                {
                    this.listTable1.Items.Remove(listTable1.SelectedItems[0]);
                }
            }
            IsHasItem();
        }

        private void btn_Del_Click(object sender, System.EventArgs e)
        {
            int c = this.listTable2.SelectedItems.Count;
            ListBox.SelectedObjectCollection objs = this.listTable2.SelectedItems;
            for (int i = 0; i < c; i++)
            {
                this.listTable1.Items.Add(listTable2.SelectedItems[i]);

            }
            for (int i = 0; i < c; i++)
            {
                if (this.listTable2.SelectedItems.Count > 0)
                {
                    this.listTable2.Items.Remove(listTable2.SelectedItems[0]);
                }
            }

            IsHasItem();
        }

        private void btn_Dellist_Click(object sender, System.EventArgs e)
        {
            int c = this.listTable2.Items.Count;
            for (int i = 0; i < c; i++)
            {
                this.listTable1.Items.Add(this.listTable2.Items[i]);
            }
            this.listTable2.Items.Clear();
            IsHasItem();
        }
        #endregion

        #region listbox操作
        private void listTable1_DoubleClick(object sender, System.EventArgs e)
        {
            if (this.listTable1.SelectedItem != null)
            {
                this.listTable2.Items.Add(listTable1.SelectedItem);
                this.listTable1.Items.Remove(this.listTable1.SelectedItem);
                IsHasItem();
            }
        }

        private void listTable2_DoubleClick(object sender, System.EventArgs e)
        {
            if (this.listTable2.SelectedItem != null)
            {
                this.listTable1.Items.Add(listTable2.SelectedItem);
                this.listTable2.Items.Remove(this.listTable2.SelectedItem);
                IsHasItem();
            }
        }

        /// <summary>
        /// 判断listbox有没有项目
        /// </summary>
        private void IsHasItem()
        {
            if (this.listTable1.Items.Count > 0)
            {
                this.btn_Add.Enabled = true;
                this.btn_Addlist.Enabled = true;
            }
            else
            {
                this.btn_Add.Enabled = false;
                this.btn_Addlist.Enabled = false;
            }
            if (this.listTable2.Items.Count > 0)
            {
                this.btn_Del.Enabled = true;
                this.btn_Dellist.Enabled = true;
                this.btn_Creat.Enabled = true;
            }
            else
            {
                this.btn_Del.Enabled = false;
                this.btn_Dellist.Enabled = false;
                this.btn_Creat.Enabled = false;
            }
        }
        #endregion

        #region 异步控件设置
        public void SetBtnEnable()
        {
            if (this.btn_Creat.InvokeRequired)
            {
                SetBtnEnableCallback d = new SetBtnEnableCallback(SetBtnEnable);
                this.Invoke(d, null);
            }
            else
            {
                this.btn_Creat.Enabled = true;
                this.btn_Cancle.Enabled = true;
            }
        }
        public void SetBtnDisable()
        {
            if (this.btn_Creat.InvokeRequired)
            {
                SetBtnDisableCallback d = new SetBtnDisableCallback(SetBtnDisable);
                this.Invoke(d, null);
            }
            else
            {
                this.btn_Creat.Enabled = false;
                this.btn_Cancle.Enabled = false;
            }
        }
        public void SetlblStatuText(string text)
        {
            if (this.labelNum.InvokeRequired)
            {
                SetlblStatuCallback d = new SetlblStatuCallback(SetlblStatuText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.labelNum.Text = text;
            }
        }
        /// <summary>
        /// 循环网址进度最大值
        /// </summary>
        /// <param name="val"></param>
        public void SetprogressBar1Max(int val)
        {
            if (this.progressBar1.InvokeRequired)
            {
                SetProBar1MaxCallback d = new SetProBar1MaxCallback(SetprogressBar1Max);
                this.Invoke(d, new object[] { val });
            }
            else
            {
                this.progressBar1.Maximum = val;

            }
        }
        /// <summary>
        /// 循环网址进度
        /// </summary>
        /// <param name="val"></param>
        public void SetprogressBar1Val(int val)
        {
            if (this.progressBar1.InvokeRequired)
            {
                SetProBar1ValCallback d = new SetProBar1ValCallback(SetprogressBar1Val);
                this.Invoke(d, new object[] { val });
            }
            else
            {
                this.progressBar1.Value = val;

            }
        }
        #endregion

        private void btn_Cancle_Click(object sender, System.EventArgs e)
        {

            if ((mythread != null) && (mythread.IsAlive))
            {
                mythread.Abort();
            }
            this.Close();
        }
        private void btn_Creat_Click(object sender, System.EventArgs e)
        {
            try
            {
                if (this.txtTargetFolder.Text == "")
                {
                    MessageBox.Show("请选择保存文件路径！", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                DbName = this.cmbDB.Text;
                pictureBox1.Visible = true;
                mythread = new Thread(new ThreadStart(ThreadWork));
                mythread.Start();
                //ThreadWork();
            }
            catch (System.Exception ex)
            {
                LogInfo.WriteLog(ex);
                MessageBox.Show(ex.Message, "完成", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }
        void ThreadWork()
        {
            try
            {
                //this.Cursor=System.Windows.Forms.Cursors.WaitCursor;
                SetBtnDisable();
                int tblCount = this.listTable2.Items.Count;
                string filename = this.txtTargetFolder.Text;

                SetprogressBar1Max(tblCount);
                SetprogressBar1Val(1);
                SetlblStatuText("0");

                #region 循环每个表

                for (int i = 0; i < tblCount; i++)
                {
                    //this.listTable2.SelectedIndex=i;
                    string tablename = this.listTable2.Items[i].ToString();
                    dsb.Fieldlist = new List<LTP.CodeHelper.ColumnInfo>();
                    dsb.CreateTabScript(DbName, tablename, filename, progressBar2);

                    SetprogressBar1Val(i + 1);
                    SetlblStatuText((i + 1).ToString());
                }
                #endregion

                SetBtnEnable();
                //this.Cursor=System.Windows.Forms.Cursors.Default;
                MessageBox.Show("脚本全部生成成功！", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (System.Exception ex)
            {
                LogInfo.WriteLog(ex);
                SetBtnEnable();
                //this.Cursor=System.Windows.Forms.Cursors.Default;
                MessageBox.Show("脚本生成失败！请检查表名是否规范或其他问题导致。(" + ex.Message + ")", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btn_TargetFold_Click(object sender, System.EventArgs e)
        {
            SaveFileDialog sqlsavedlg = new SaveFileDialog();
            sqlsavedlg.Title = "保存当前脚本";
            sqlsavedlg.Filter = "sql files (*.sql)|*.sql|All files (*.*)|*.*";
            DialogResult result = sqlsavedlg.ShowDialog(this);
            if (result == DialogResult.OK)
            {
                this.txtTargetFolder.Text = sqlsavedlg.FileName;
            }
        }



    }
}
